// 文件名称：bind.js
// 完整保存路径：miniprogram/pages/bind/bind.js
// 功能说明：学生绑定页面逻辑控制
// 使用说明：处理学生信息绑定功能

const { bindStudent, isLoggedIn, computeUserStatus, getUserProfile } = require('../../utils/auth.js');

Page({
  data: {
    bindForm: {
      education_id: '',
      student_name: '',
      parent_phone: ''
    },
    loading: false,
    bindResult: null,
    alreadyBound: false,
    existingStudent: null,
    rebindMode: false
  },

  onLoad() {
    if (!isLoggedIn()) {
      wx.showToast({ title: '请先登录', icon: 'error' });
      wx.navigateBack();
      return;
    }
  },

  onShow() {
    // 每次显示尝试同步当前绑定状态
    this.initializeBindingState();
  },

  async initializeBindingState() {
    const { status, userInfo } = computeUserStatus();
    if (status === 'complete' && userInfo && (userInfo.studentInfo || userInfo.student)) {
      const studentInfo = userInfo.studentInfo || userInfo.student;
      this.setData({
        alreadyBound: true,
        existingStudent: studentInfo,
        rebindMode: false
      });
      return;
    }
    // 若本地无，尝试服务器刷新
    try {
      const fresh = await getUserProfile();
      if (fresh && (fresh.studentInfo || fresh.student)) {
        const studentInfo = fresh.studentInfo || fresh.student;
        this.setData({ alreadyBound: true, existingStudent: studentInfo, rebindMode: false });
      } else {
        this.setData({ alreadyBound: false, existingStudent: null });
      }
    } catch (e) {
      console.warn('刷新用户资料失败', e);
    }
  },

  onInputChange(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;
    
    this.setData({
      [`bindForm.${field}`]: value
    });
  },

  async handleBind() {
    const { education_id, student_name, parent_phone } = this.data.bindForm;
    
    if (!education_id.trim() || !student_name.trim() || !parent_phone.trim()) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'error'
      });
      return;
    }

    try {
  this.setData({ loading: true });
      
      const result = await bindStudent({
        education_id: education_id.trim(),
        student_name: student_name.trim(),
        parent_phone: parent_phone.trim()
      });
      
      const studentObj = result.student_info || result.student || (result.studentInfo ? result.studentInfo : null);
      this.setData({
        loading: false,
        bindResult: result,
        alreadyBound: !!studentObj,
        existingStudent: studentObj,
        rebindMode: false
      });
      
      wx.showToast({
        title: '绑定成功',
        icon: 'success'
      });
      
      // 绑定成功后更新全局用户状态
  const app = getApp();
  app.globalData.userStatus = 'complete';
      
      setTimeout(() => {
        wx.showModal({
          title: '绑定成功',
            content: '学生信息绑定成功！是否返回首页？',
            confirmText: '返回首页',
            cancelText: '留在此页',
            success: (res) => {
              if (res.confirm) {
                wx.switchTab({ url: '/pages/welcome/welcome' });
              }
            }
        });
      }, 800);
      
    } catch (error) {
      this.setData({ loading: false });
      
      // 根据错误类型显示不同的处理方式
      if (error.message.includes('不匹配') || error.message.includes('不存在') || error.message.includes('未找到')) {
        wx.showModal({
          title: '绑定失败',
          content: `${error.message}\n\n如需帮助请联系系统管理员：\n电话：400-123-4567\n工作时间：周一至周五 9:00-18:00`,
          showCancel: false,
          confirmText: '知道了'
        });
      } else {
        wx.showToast({
          title: error.message || '绑定失败',
          icon: 'error'
        });
      }
    }
  },

  resetForm() {
    this.setData({
      bindForm: {
        education_id: '',
        student_name: '',
        parent_phone: ''
      },
      bindResult: null,
      rebindMode: true
    });
  },

  enterRebindMode() {
    this.setData({ rebindMode: true });
  },
  cancelRebind() {
    // 返回已绑定信息视图
    this.setData({ rebindMode: false });
  }
}); 